package com.example.bdd.demo.base.config;

import com.example.bdd.demo.utils.FileUtil;
import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;

import java.util.*;
import java.util.concurrent.TimeUnit;

public class BddBaseConfig {

    private BddBaseConfig() {
    }

    public static WebDriver getInstance(String domain) {
        return EnumSingleton.SingletonFactory.getDriver(domain);
    }

    private enum EnumSingleton {
        SingletonFactory;

        public WebDriver getDriver(String domain) {
            return initWebDriver(domain);
        }

        private WebDriver initWebDriver(String domain){
            Map<String, String> config = this.getConfig();
            System.setProperty("webdriver.chrome.driver", config.get("WebDriverChromeDriverPath"));
            WebDriver webDriver = new ChromeDriver();
            if ("DOMAIN1".equalsIgnoreCase(domain)) {
                webDriver.get(config.get("WEBDRIVER_URL_DOMAIN1"));
            } else {
                webDriver.get(config.get("WEBDRIVER_URL_DOMAIN2"));
            }
            webDriver.manage().window().setSize(new Dimension(800, 700));
            webDriver.manage().window().setPosition(new Point(400, 0));
            webDriver.manage().timeouts().implicitlyWait(Long.valueOf(config.get("WEBDRIVER_TIMEOUT")), TimeUnit.SECONDS);
            PageFactory.initElements(webDriver, this);
            return webDriver;
        }

        public Map<String, String> getConfig() {
            Set<String> contents = FileUtil.readFileByLines("src\\test\\resources\\bdd-config.properties");
            Iterator<String> iterator = contents.iterator();
            Map<String, String> config = new TreeMap<>();
            while (iterator.hasNext()){
                String line = iterator.next();
                if (StringUtils.isNotBlank(line)) {
                    String[] strings = line.split("=");
                    config.put(strings[0].trim(), strings[1].trim());
                }
            }
            return config;
        }
    }

}
